from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from . import constants


def generate_save_user_token(openid):
    """
    将明文openid序列化成密文openid
    生成保存用户数据的token
    :param openid: 用户的openid(明文openid)
    :return: token(密文openid)
    """""
    # 创建序列化器对象
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    # 构造原始的数据
    data = {'openid': openid}
    # 序列化字典:dumps返回bytes类型的数据
    token = serializer.dumps(data)

    return token.decode()


def check_save_user_token(access_token):
    """
    检验保存用户数据的token
    将密文openid转成明文openid
    :param token: token   密文openid
    :return: openid or None    明文openid
    """""
    # 　创建序列化器
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
    try:
        # 　解码密文openid
        data = serializer.loads(access_token)
        # openid = data.get('openid')
    except BadData:
        return None
    else:
        # return openid
        return data.get('openid')
